<?php

namespace app\common\model;

use app\common\library\MemberVo;
use app\common\traits\TimeToStringTrait;
use think\Db;
use think\Env;
use think\Exception;
use think\Model;

/**
 * 模型
 */
class OrderCommission extends Model
{
    use TimeToStringTrait;

    // 表名
    protected $name = '';
    protected $deleteTime = false;
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [

    ];


    public function member()
    {
        return $this->belongsTo('member', 'member_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function shop()
    {
        return $this->belongsTo('shop', 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function car()
    {
        return $this->belongsTo('car', 'car_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function agent()
    {
        return $this->belongsTo('agent', 'agent_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function order()
    {
        return $this->belongsTo('order', 'order_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function orderGoods()
    {
//        return $this->belongsTo('OrderGoods', 'order_id', 'order_id', [], 'LEFT')->setEagerlyType(0);
        return $this->hasMany('OrderGoods', 'order_id');
    }


    public static function addRecord($order_id)
    {
        $order_info = Order::get($order_id, ['orderGoods']);//获取订单信息
        $ratio = bcsub($order_info['ratio'], 0, 3);//代理商佣金比例 3位小数
        $profit = bcsub($order_info['pay_amount'], $order_info['cost'], 3);//获取利润金额 （实际支付金额 - 成本）
        if ($profit < 0){
            $profit = 0;
        }
        $money = bcmul($profit, $ratio, 3);
        self::create([
            'order_id' => $order_info['id'],
            'order_sn' => $order_info['order_sn'],
            'agent_id' => $order_info['agent_id'],
            'member_id' => $order_info['member_id'],
            'shop_id' => $order_info['shop_id'],
            'order_amount' => $order_info['order_amount'],
            'pay_amount' => $order_info['pay_amount'],
            'cost' => $order_info['cost'],
            'car_id' => $order_info['car_id'],
            'goods_id' => $order_info['order_goods'][0]['goods_id'],
            'goods_name' => $order_info['order_goods'][0]['goods_name'],
            'status' => 0,
            'ratio' => $ratio,
            'money' => $money,
        ]);
        return true;
    }




}
